package com.cocolove2.andbase.http;

import android.Manifest;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;

import com.cocolove2.andbase.BaseActivity;
import com.cocolove2.andbase.R;
import com.cocolove2.andbase.bean.Weather;
import com.cocolover2.andbase.adapterdelegates.AbsAdapterDelegateBase;
import com.cocolover2.andbase.adapterdelegates.AbsSampleAdapterDelegate;
import com.cocolover2.andbase.adapterdelegates.BaseDelegationAdapter;
import com.cocolover2.andbase.adapterdelegates.RecyclerViewHolder;
import com.cocolover2.andbase.utils.FileUtil;
import com.cocolover2.andbase.utils.log.KLog;
import com.google.gson.Gson;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.functions.Consumer;
import okhttp3.Call;

/**
 * 网络请求测试
 * Created by cocolove2 on 18/1/29.
 */

public class HttpTestActivity extends BaseActivity<IHttpView, HttpTestPresenter> implements IHttpView {
    List<String> mDatas = new ArrayList<>();
    BaseDelegationAdapter<List<String>> mAdapter;

    RecyclerView mRecyclerView;
    private List<Call> mCallList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRecyclerView = (RecyclerView) findViewById(R.id.main_index_rv);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mDatas.addAll(buildItemDatas());
        mAdapter = new BaseDelegationAdapter<List<String>>(mDatas);
        MyDelegate delegate = new MyDelegate(this);
        mAdapter.addDelegate(delegate);
        delegate.setOnItemClickListener(new AbsAdapterDelegateBase.OnItemClikListener() {
            @Override
            public void onItemClicked(int viewType, int position) {
                handleItemClick(position);
            }
        });
        mRecyclerView.setAdapter(mAdapter);
    }

    @Override
    protected HttpTestPresenter createPresenter() {
        return new HttpTestPresenter();
    }

    private class MyDelegate extends AbsSampleAdapterDelegate<String, String> {

        MyDelegate(Context context) {
            super(context, R.layout.item_main_index, 1);
        }

        @Override
        public void onBindData(RecyclerViewHolder holder, int position, String item) {
            holder.setText(R.id.item_main_index_btn, item);
        }

        @Override
        public boolean isForViewType(@NonNull List<String> items, int position) {
            return true;
        }
    }

    private void showResonseDialog(String title, String msg) {
        new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(msg)
                .setCancelable(false)
                .setPositiveButton("关闭", null)
                .show();
    }

    private void handleItemClick(int position) {
        switch (position) {
            case 0:
                mPresenter.getBaidu();
                break;
            case 1:
                mPresenter.getWeather();
                break;
            case 2:
                mPresenter.getWeather2();
                break;
            case 3:
                Call call = mPresenter.downloadFile("http://d.lanrentuku.com/down/tupian/1707/011321195_lanrentuku.com.zip");
                mCallList.add(call);
                break;
            case 4:
                new RxPermissions(this).request(Manifest.permission.READ_EXTERNAL_STORAGE)
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean aBoolean) throws Exception {
                                if (aBoolean) {
                                    uploadTest();
                                }
                            }
                        });
                break;
            case 5:
                mPresenter.getBaidu2();
                break;
            default:
                Toast.makeText(this, "敬请期待", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    private void uploadTest() {
        Map<String, Object> params = new HashMap<>();
        params.put("title", "Hello world");
        String path = FileUtil.getSDPath() + File.separator + "test.mp4";
        if (!new File(path).exists()) {
            KLog.e("上传文件不存在");
            Toast.makeText(this, "找不到文件:" + path, Toast.LENGTH_SHORT).show();
            return;
        }
        params.put("upload", new File(path));
        Call uploadCall = mPresenter.uploadFiles("http://api.nohttp.net/upload", params);
        mCallList.add(uploadCall);
    }

    @Override
    protected void onDestroy() {
        for (Call call : mCallList) {
            if (call != null && !call.isCanceled()) {
                call.cancel();
            }
        }
        super.onDestroy();

    }

    private List<String> buildItemDatas() {
        List<String> datas = new ArrayList<>();
        datas.add("百度Get请求");
        datas.add("获取厦门天气信息");
        datas.add("获取厦门天气信息2");
        datas.add("文件下载");
        datas.add("文件上传");
        datas.add("多Apiservice请求支持");
        return datas;
    }

    @Override
    public void onBaiduResult(String data, int code, String msg) {
        if (code == 0) {
            showResonseDialog("百度请求", data);
        } else {
            showResonseDialog("百度请求", msg);
        }
    }

    @Override
    public void onWeatherInfo(Weather weather, int code, String msg) {
        if (weather != null) {
            String content = new Gson().toJson(weather, Weather.class);
            showResonseDialog("天气结果", content);
        } else {
            showResonseDialog("天气结果", code + "#" + msg);
        }
    }

    @Override
    public void onDownloadInfo(final String path, final int code, final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (code == 0) {
                    showResonseDialog("下载结果(在子线程中回调)", path);
                } else {
                    showResonseDialog("下载结果(在子线程中回调)", msg);
                }
            }
        });

    }

    @Override
    public void onUploadInfo(final String result, final int code, final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (code == 0) {
                    showResonseDialog("上传结果(在子线程中回调)", result);
                } else {
                    showResonseDialog("上传结果(在子线程中回调)", msg);
                }
            }
        });

    }


}
